import { StyleSheet, Text, View, ScrollView, Pressable, TextInput, Modal } from 'react-native';
import React, { useEffect, useState } from 'react';
import FastImage from '@d11/react-native-fast-image';
import ImagePicker from 'react-native-image-crop-picker';
import { useTranslation } from 'react-i18next';
import { NavBarHeader } from '~/components';
import { userStore, observer } from '~/store';
import { px2dp, scale, width } from '~/utils/px2dp';
import { getUserInfo, updateUserInfo } from '~/api/loginApi';
import { useUploadImage } from '~/common';
import { onePx } from '~/utils/px2dp';
import PickerModalData from './components/PickerModalData';
import SelectWeightModal from './components/SelectWeightModal';
import SelectHeightModal from './components/SelectHeightModal';

export default observer(() => {
    const { t } = useTranslation();
    const [loading, setLoading] = useState(false);
    const [formData, setFormData] = useState({
        avatar: '',
        armarium_science_user_name: '',
        armarium_science_user_sex: 1, //性别
        armarium_science_user_tz: 0, // 体重
        armarium_science_user_sg: 0, // 身高
        armarium_science_user_birthday: '', //年龄
    });
    // 年龄
    const [ageVisible, setAgeVisible] = useState(false);
    // 性别
    const genderData = [
        { id: 2, title: '男性' },
        { id: 1, title: '女性' },
    ];
    // 体重
    const [visible, setVisible] = useState(false);
    // 身高
    const [heVisible, setHeVisible] = useState(false);
    const getData = () => {
        getUserInfo().then((res) => {
            const {
                avatar,
                armarium_science_user_birthday,
                armarium_science_user_id,
                armarium_science_user_name,
                armarium_science_user_sex,
                armarium_science_user_sg,
                armarium_science_user_tz,
            } = res.data.user_info;
            setFormData({
                ...formData,
                avatar: avatar,
                armarium_science_user_name: armarium_science_user_name,
                armarium_science_user_sex,
                armarium_science_user_sg,
                armarium_science_user_tz,
                armarium_science_user_birthday,
            });
            const data = {
                avatar: avatar,
                armarium_science_user_name,
                sex: armarium_science_user_sex,
            };
            userStore.changeUserInfo(data);
        });
    };
    const uploadAvatar = async () => {
        setLoading(true);
        ImagePicker.openPicker({
            width: 300,
            height: 400,
            cropping: true,
        })
            .then((image: any) => {
                useUploadImage(image)
                    .then((res: any) => {
                        setFormData({ ...formData, avatar: res });
                        setLoading(false);
                    })
                    .catch((err) => {
                        setLoading(false);
                        setFormData({ ...formData, avatar: image?.path });
                    });
            })
            .catch((err) => {
                setLoading(false);
            });
    };
    const saveUser = () => {
        const data = {
            name: formData.armarium_science_user_name, //用户名
            height: formData.armarium_science_user_sg, //体重
            birth: formData.armarium_science_user_birthday, //生日
            weight: formData.armarium_science_user_tz, //体重
            sex: formData.armarium_science_user_sex, //性别
            avatar: formData.avatar, // 头像
            avatar_url: formData.avatar,
        };
        updateUserInfo(data).then((res) => {
            if (res.status == 1) {
                Toast.show({ content: '更新用户信息成功' });
                getData();
            } else {
                Toast.show({ content: '更新用户信息失败' });
            }
        });
    };
    useEffect(() => {
        getData();
    }, []);
    return (
        <View style={styles.container}>
            <NavBarHeader title={t('EditUserInfo.title')} />
            <ScrollView showsVerticalScrollIndicator={false} contentContainerStyle={styles.contentStyle}>
                <Pressable style={styles.avatars} onPress={uploadAvatar}>
                    <FastImage
                        source={{
                            uri: formData.avatar
                                ? formData.avatar
                                : 'https://bjy-crmeb.oss-cn-shenzhen.aliyuncs.com/attach/2025/05/58476202505201200156452.png',
                        }}
                        style={styles.avatar}
                        resizeMode={FastImage.resizeMode.cover}
                    />
                </Pressable>
                <View style={styles.listItem}>
                    <Text style={styles.input_title}>昵称</Text>
                    <TextInput
                        value={formData.armarium_science_user_name}
                        placeholder={formData.armarium_science_user_name || '请输入昵称'}
                        placeholderTextColor={'#6D6F81'}
                        onChangeText={(val) =>
                            setFormData({
                                ...formData,
                                armarium_science_user_name: val,
                            })
                        }
                        style={styles.inputStyle}
                    />
                </View>
                <Pressable
                    style={[styles.listItem, { justifyContent: 'space-between', height: px2dp(80) }]}
                    onPress={() => setHeVisible(true)}>
                    <Text style={styles.input_title}>身高（cm）</Text>
                    <Text style={[styles.genderText]}>
                        {formData.armarium_science_user_sg > 0 ? formData.armarium_science_user_sg : '请选择身高'}
                    </Text>
                </Pressable>
                <Pressable
                    style={[styles.listItem, { justifyContent: 'space-between', height: px2dp(80) }]}
                    onPress={() => setVisible(true)}>
                    <Text style={styles.input_title}>体重（kg）</Text>
                    <Text style={[styles.genderText]}>
                        <Text style={styles.genderText}>
                            {formData.armarium_science_user_tz > 0
                                ? formData.armarium_science_user_tz.toString()
                                : '请选择体重'}
                        </Text>
                    </Text>
                </Pressable>
                <View style={styles.listItem}>
                    <Text style={styles.input_title}>性别</Text>
                    <View style={[styles.row, { justifyContent: 'flex-end', width: width - px2dp(248) }]}>
                        {genderData.map((item, index) => {
                            return (
                                <Pressable
                                    style={[
                                        styles.listGender,
                                        formData.armarium_science_user_sex == item.id && { backgroundColor: '#25C8C8' },
                                    ]}
                                    key={item.id}
                                    onPress={() =>
                                        setFormData({
                                            ...formData,
                                            armarium_science_user_sex: item.id,
                                        })
                                    }>
                                    <Text
                                        style={[
                                            styles.genderText,
                                            formData.armarium_science_user_sex == item.id && { color: '#fff' },
                                        ]}>
                                        {item.title}
                                    </Text>
                                </Pressable>
                            );
                        })}
                    </View>
                </View>
                <Pressable
                    style={[styles.listItem, { justifyContent: 'space-between', height: px2dp(80) }]}
                    onPress={() => setAgeVisible(true)}>
                    <Text style={styles.input_title}>出生日期</Text>
                    <Text style={[styles.genderText]}>
                        {formData.armarium_science_user_birthday || '请选择出生日期'}
                    </Text>
                </Pressable>
                <Pressable style={[styles.bt, styles.row]} onPress={saveUser}>
                    <Text style={styles.bt_text}>保存信息</Text>
                </Pressable>
            </ScrollView>
            {/* 选择年龄 */}
            <PickerModalData
                defaultDate={'1970-10-01'}
                visible={ageVisible}
                cancel={() => setAgeVisible(false)}
                confirm={(res) => {
                    setFormData({
                        ...formData,
                        armarium_science_user_birthday: res,
                    });
                    setAgeVisible(false);
                }}
            />
            {/* 选择体重 */}
            <SelectWeightModal
                visible={visible}
                onToggleVisible={() => setVisible(false)}
                onConfirm={(res) => {
                    setFormData({
                        ...formData,
                        armarium_science_user_tz: res,
                    });
                }}
            />
            {/* 选择身高 */}
            <SelectHeightModal
                visible={heVisible}
                onToggleVisible={() => setHeVisible(false)}
                onConfirm={(res) => {
                    console.log('trsersesrsersesrsersss', res);
                    setFormData({
                        ...formData,
                        armarium_science_user_sg: res,
                    });
                }}
            />
        </View>
    );
});

const styles = StyleSheet.create({
    row: {
        flexDirection: 'row',
        alignItems: 'center',
    },

    container: {
        flex: 1,
        backgroundColor: '#fff',
    },
    contentStyle: {
        flexGrow: 1,
        paddingBottom: '20%',
    },
    avatars: {
        alignSelf: 'center',
        marginVertical: px2dp(64),
    },
    avatar: {
        width: px2dp(160),
        height: px2dp(160),
        borderRadius: px2dp(90),
    },
    listItem: {
        margin: px2dp(24),
        flexDirection: 'row',
        alignItems: 'center',
        borderBottomWidth: onePx * 3,
        borderColor: '#eee',
    },
    input_title: {
        fontSize: scale(28),
        width: px2dp(200),
    },
    inputStyle: {
        height: px2dp(80),
        fontSize: scale(30),
        textAlign: 'right',
        color: '#000',
        width: width - px2dp(248),
    },
    listGender: {
        backgroundColor: '#F4F4F4',
        justifyContent: 'center',
        alignItems: 'center',
        width: px2dp(148),
        height: px2dp(70),
        borderRadius: px2dp(8),
        marginLeft: px2dp(48),
        marginBottom: px2dp(12),
    },
    genderText: {
        fontSize: scale(32),
        color: '#343436',
        fontWeight: 'bold',
    },
    bt: {
        justifyContent: 'center',
        backgroundColor: '#25C8C8',
        height: px2dp(96),
        borderRadius: px2dp(50),
        marginHorizontal: px2dp(64),
        marginTop: '20%',
    },
    bt_text: {
        color: '#fff',
        fontSize: scale(32),
        fontWeight: 'bold',
    },
});
